package com.kimu.user.service;

import java.util.List;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kimu.user.entity.Authority;
import com.kimu.user.entity.User;
import com.kimu.user.mapper.AuthorityMapper;
import com.kimu.user.mapper.UserMapper;

@Service
public class CustomUserDetailsService implements UserDetailsService {

	private UserMapper userMapper;
	
	private AuthorityMapper authorityMapper;
	
	public CustomUserDetailsService(UserMapper userMapper, AuthorityMapper authorityMapper) {
		this.userMapper = userMapper;
		this.authorityMapper = authorityMapper;
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
		if (null != user) {
			// 查询用户权限
			List<Authority> authorities = authorityMapper.selectList(new QueryWrapper<Authority>().eq("user_id", user.getId()));
			user.setAuthorities(authorities);
			return user;
		}
		throw new UsernameNotFoundException("User '" + username + "' not found!");
	}

	
}
